//
//  HTTPRequestHelper.m
//  eBook
//
//  Created by Pham Vu Duong 16/11/2011
//  Copyright 2011 CMCSoft. All rights reserved.
//

#import "TumblrRequestHelper.h"
#import "JSON.h"
#import "Photo.h"
#import "DatabaseConnection.h"
#import "ASIHttpRequest.h"

#import "CMCOperationQueue.h"
#import "TestFlight.h"

#define HOST @"http://www.reacticons.com/api/read/json?type=photo"
#define ARG_TAGGED @"&tagged="
#define ARG_START @"&start="
#define ARG_QUANTITY @"&num="
#define MAX_QUANTITY 50

#define kTumblrRequestAllListPhotoSuccess @"kTumblrRequestAllListPhotoSuccess"
#define kTumblrRequestAllListPhotoFailure @"kTumblrRequestAllListPhotoFailure"

#define kTumblrRequestBlockPhotoSuccess @"kTumblrRequestBlockPhotoSuccess"
#define kTumblrRequestBlockPhotoFailure @"kTumblrRequestBlockPhotoFailure"


#define NUMBER_OF_TUMBLR_LIST @"NUMBER_OF_TUMBLR_LIST"

@implementation TumblrRequestHelper
@synthesize isSecondTime;

- (id)init
{
    self = [super init];
    if (self) {
        itemList=[[NSMutableArray alloc] init];
        isSecondTime=NO;
        // Initialization code here.
    }
    
    return self;
}

- (void)requestWithURL:(NSURL*)_url
           andDelegate:(id)_delegate
    andSuccessSelector:(SEL)_successSelector
    andFailureSelector:(SEL)_failureSelector

{

   ASIHTTPRequest* _request = [[[ASIHTTPRequest alloc] initWithURL:_url] autorelease];
    [_request setDelegate:_delegate];
    [_request setDidFinishSelector:_successSelector];
    [_request setDidFailSelector:_failureSelector];
    [_request performSelector:@selector(startAsynchronous) withObject:nil afterDelay:0.1];

}



#pragma mark - get list tumblr

-(void)getListTumblr{
    [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"UPDATING_DATA"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSString* urlString=[NSString stringWithFormat:@"%@%@0%@0",HOST,ARG_START,ARG_QUANTITY];
    [self requestWithURL:[NSURL URLWithString:urlString]
             andDelegate:self
      andSuccessSelector:@selector(requestListPhotoInfoSuccess:)
      andFailureSelector:@selector(requestListPhotoInfoFailure:)];
}


-(void)getBlockTumblrFromIndex:(NSNumber*)index{
    NSString* urlString=[NSString stringWithFormat:@"%@%@%d%@50",HOST,ARG_START,[index intValue],ARG_QUANTITY];
    [self requestWithURL:[NSURL URLWithString:urlString]
             andDelegate:self
      andSuccessSelector:@selector(requestListPhotoSuccess:)
      andFailureSelector:@selector(requestListPhotoFailure:)];
}


#pragma mark - HTTPRequestHelper Delegate

- (void)requestListPhotoInfoSuccess:(ASIHTTPRequest *)request
{
    NSString *resultString=[request.responseString substringFromIndex:22];
    resultString=[resultString substringToIndex:resultString.length-2];
    
    DBLOG(@"%@",[resultString JSONValue]);
    NSNumber *totalPost=[(NSDictionary*)[resultString JSONValue] objectForKey:@"posts-total"];
    if ([totalPost isEqualToNumber:[[NSUserDefaults standardUserDefaults] objectForKey:NUMBER_OF_TUMBLR_LIST]]) {
        [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"UPDATING_DATA"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];
        NSLog(@"\n\n------------------\n\nNO NEW PHOTO\n\n-------------\n\n\n");
        [TestFlight passCheckpoint:@"NO NEW PHOTO"];

        return;
    }
    DBLOG(@"CMCTumblrRequestHelper - requestTumblrList - %d",[totalPost intValue]);
    hasSentOK=NO;
    totalCount=[totalPost intValue]/50+1;
    successCount=0;
    failureCount=0;
    hasSentOK=NO;

    for (int i=0; i<[totalPost intValue]/50+1; i++) {
        [self getBlockTumblrFromIndex:[NSNumber numberWithInt:i*50]];
    }
}

- (void)requestListPhotoInfoFailure:(ASIHTTPRequest *)request{
    DBLOG(@"TumblrRequestHelper - requestListPhotoInfoFailure - %d",request.responseStatusCode);
    [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
    [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"UPDATING_DATA"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoFailure object:nil];

}

- (void)requestListPhotoSuccess:(ASIHTTPRequest *)request{
    successCount++;
    if (!hasSentOK) {
        if (successCount>totalCount/10) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestBlockPhotoSuccess object:nil];
            hasSentOK=YES;
        }
    }
    DBLOG(@"TumblrRequestHelper - requestListPhotoSuccess - %d",request.responseStatusCode);
    NSString *resultString=[request.responseString substringFromIndex:22];
    resultString=[resultString substringToIndex:resultString.length-2];
    
    NSArray*list =[NSArray arrayWithArray:[(NSDictionary*)[resultString JSONValue] objectForKey:@"posts"]];
    
    if ([list count]>0) {
//        NSMutableArray *itemList=[[[NSMutableArray alloc] init] autorelease];
        for (NSDictionary *item in list) {
            Photo *photo=[[Photo alloc] init];
            photo.photo100URL=[item objectForKey:@"photo-url-100"];
            photo.photo75URL=[item objectForKey:@"photo-url-75"];
            photo.photo250URL=[item objectForKey:@"photo-url-250"];
            photo.photoImage=[item objectForKey:@"photo-url-1280"];
            photo.photoThumbnail=[item objectForKey:@"photo-url-250"];
            photo.photoCreatedDate=[item objectForKey:@"date-gmt"];
            photo.photoID=[NSString stringWithFormat:@"%@",[item objectForKey:@"id"]];
            photo.categoryName=[NSString stringWithFormat:@";%@;",[[item objectForKey:@"tags"] componentsJoinedByString:@";"]];
            photo.photoName=[item objectForKey:@"photo-url-1280"];
            photo.photoRecentlyUsed=@"19990102030405";
            [itemList addObject:[photo itemObject]];
            [photo release];
        }
    }

    
    if (successCount==totalCount){
        if (isSecondTime){
            [[CMCOperationQueue sharedInstance] addOperation:[[NSInvocationOperation alloc] initWithTarget:[DatabaseConnection class] selector:@selector(updateListPhotos:) object:itemList]];
        }
        else{
            [DatabaseConnection updateListPhotos:itemList];
        }
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:itemList.count] forKey:NUMBER_OF_TUMBLR_LIST];
        
        [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"UPDATING_DATA"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];
        
    }
    
    else if (successCount+failureCount==totalCount){
        if (isSecondTime){
            [[CMCOperationQueue sharedInstance] addOperation:[[NSInvocationOperation alloc] initWithTarget:[DatabaseConnection class] selector:@selector(updateListPhotos:) object:itemList]];
        }
        else{
            [DatabaseConnection updateListPhotos:itemList];
        }
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:itemList.count] forKey:NUMBER_OF_TUMBLR_LIST];
        
        [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"UPDATING_DATA"];
        [[NSUserDefaults standardUserDefaults] synchronize];


        //TODO: notify all finish and has failure
        [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];

    }
}

- (void)requestListPhotoFailure:(ASIHTTPRequest *)request{
    DBLOG(@"TumblrRequestHelper - requestListPhotoFailure - %d",request.responseStatusCode);

    failureCount++;
    if (failureCount==totalCount) {
        
        [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"UPDATING_DATA"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoFailure object:nil];

    }
    else if (successCount+failureCount==totalCount){
        //TODO: notify all finish and has failure
        [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"UPDATING_DATA"];

        if (isSecondTime){
            [[CMCOperationQueue sharedInstance] addOperation:[[NSInvocationOperation alloc] initWithTarget:[DatabaseConnection class] selector:@selector(updateListPhotos:) object:itemList]];
        }
        else{
            [DatabaseConnection updateListPhotos:itemList];
        }
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:itemList.count] forKey:NUMBER_OF_TUMBLR_LIST];
        [[NSUserDefaults standardUserDefaults] synchronize];

        [[NSNotificationCenter defaultCenter] postNotificationName:kTumblrRequestAllListPhotoSuccess object:nil];

    }

}



@end
